<template>

  <div>
    <el-breadcrumb separator="/" style="color: black;font-weight: 700">
      <el-breadcrumb-item >首页</el-breadcrumb-item>
      <el-breadcrumb-item>航班管理</el-breadcrumb-item>
      <el-breadcrumb-item>机场信息</el-breadcrumb-item>
    </el-breadcrumb>
    <h1>机场信息管理</h1>
    <!--      搜索表单-->
    <el-row :gutter="24">
      <el-col :span="3">
        <el-button type="primary" @click="openAddDialog">添加</el-button>
      </el-col>
      <el-col :span="5">
        <el-form-item label="航班号" >
          <el-input placeholder="航班号" v-model="searchCriteria.META_ID" clearable />
        </el-form-item>
      </el-col>
      <el-col :span="5">
        <el-form-item label="中文名" >
          <el-input placeholder="中文名" v-model="searchCriteria.CNNM" clearable />
        </el-form-item>
      </el-col>
      <el-col :span="5">
        <el-form-item label="英文名" >
          <el-input placeholder="英文名" v-model="searchCriteria.ENNM" clearable />
        </el-form-item>
      </el-col>
      <el-col :span="6">
        <el-form-item>
          <el-button type="primary" @click="searchOnSubmit">{{ buttonLabel }}</el-button>
          <el-button @click="searchOnReset">取消</el-button>
        </el-form-item>
      </el-col>
    </el-row>


    <el-table :data="tableData" style="width: 100%">
      <el-table-column
          :prop="item.prop"
          :label="item.label"
          v-for="(item, index) in tableHeader"
          :key="item.prop"
      >
        <template #default="scope">
          <div
              v-show="item.editable || scope.row.editable"
              class="editable-row"
          >
            <template v-if="item.type === 'input'">
              <el-input
                  v-bind="{ readonly: ['ID', 'META_ID'].includes(item.prop) && scope.row.editable }"
                  size="small"
                  v-model="scope.row[item.prop]"
                  :placeholder="`请输入${item.label}`"
                  @change="handleEdit(scope.$index, scope.row)"
              />
            </template>
              <template v-else-if="item.type === 'select'">
                  <!-- 新增：对于类型为'select'的列 -->
                  <el-select
                          v-model="scope.row[item.prop]"
                          :value="scope.row[item.prop]"
                          size="small"
                          @change="handleEdit(scope.$index, scope.row)"
                  >
                      <el-option
                              v-for="option in item.options"
                              :key="option.value"
                              :label="option.label"
                              :value="option.value"
                      />
                  </el-select>
              </template>

          </div>
          <div
              v-show="!item.editable && !scope.row.editable"
              class="editable-row"
          >
            <span class="editable-row-span">{{ scope.row[item.prop] }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template #default="scope">
            <el-button
                    v-show="!scope.row.editable"
                    size="small"
                    @click="scope.row.editable = true"
            >编辑信息</el-button
            >
          <el-button
              v-show="scope.row.editable"
              size="small"
              type="success"
              @click="saveEditedRow(scope.row)"
          >确定</el-button
          >
          <el-button
              v-show="scope.row.editable"
              size="small"
              type="warning"
              @click="cancelEdit(scope.row)"
          >取消</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <!--     分页组件示例 -->
    <el-pagination
        :current-page="currentPage"
        v-model="currentPage"
        :small="small"
        :disabled="disabled"
        :background="background"
        :page-size="pageSize"
        layout="prev, pager, next, jumper"
        :total=totalElements
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        v-if="showPagination"
        />
    <!-- 新的分页组件，用于搜索结果 -->
    <el-pagination
        v-if="showSearchPagination"
        background
        :total="searchTotalElements"
        :current-page="searchCurrentPage"
        :page-size="searchPageSize"
        @current-change="handleSearchPageChange"
        style="margin-top: 20px;"
        v-model="currentPage"
        :small="small"
        :disabled="disabled"
        :background="background"
        layout="prev, pager, next, jumper"
        @size-change="handleSizeChange"
    />


    <!-- 添加航班信息模态框 -->
    <el-dialog v-model="dialogVisible" title="添加机场信息" width="50%" @close="resetAddForm">
      <el-form ref="addFormRef" :model="newFlight" label-width="80px">
        <el-form-item label="航班号">
          <el-input v-model="newFlight.metaid"  placeholder="请输入航班号" />
        </el-form-item>
        <el-form-item label="三字码">
          <el-input v-model="newFlight.code" placeholder="请输入机场三字码" />
        </el-form-item>
        <el-form-item label="中文名">
          <el-input v-model="newFlight.cnnm" placeholder="请输入机场中文名" />
        </el-form-item>
        <el-form-item label="英文名">
          <el-input v-model="newFlight.ennm"  placeholder="请输入机场英文名"/>
        </el-form-item>
        <el-form-item label="是否开启">
          <el-input v-model="newFlight.aiso"  placeholder="请输入机场是否开启，O表示开启，C表示关闭"/>
        </el-form-item>
        <el-form-item label="所属航站">
          <el-input v-model="newFlight.apsn"  placeholder="请输入机场所属航站"/>
        </el-form-item>
        <!-- 其他字段... -->
      </el-form>
      <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="onAddHandler">确定</el-button>
      </span>
      </template>
    </el-dialog>
  </div>
</template>


<script setup>
import { ref, reactive, onMounted,onUpdated,computed,nextTick } from 'vue';
import {ElMessage, ElMessageBox} from 'element-plus'
import axios from 'axios';
import {number} from "echarts"; // 确保已导入axios

const small = ref(false)
const background = ref(true)
const disabled = ref(false)

const handleSizeChange = (val) => {
  console.log(`${val} items per page`)
}
// 定义表单数据
const item = reactive({
  ID: '',
  META_ID: '',
  CODE: "",
  CNNM: "",
  ENNM: '',
  AISO: '',
  APSN: '',
    VALID: "",
    displayStatus:"",
});

const header = {
  prop: "key",
  label: "自定义",
  editable: false,
  type: "input",
};

const tableHeader = ref([
  // {
  //   prop: "ID",
  //   label: "ID",
  //   editable: false,
  //   type: "input"
  // },
  {
    prop: "META_ID",
    label: "航班号",
    editable: false,
    type: "input"
  },
  {
    prop: "CODE",
    label: "机场三字码",
    editable: false,
    type: "input"
  },
  {
    prop: "CNNM",
    label: "机场中文名",
    editable: false,
    type: "input"
  },
  {
    prop: "ENNM",
    label: "机场英文名",
    editable: false,
    type: "input"
  },
  {
    prop: "AISO",
    label: "机场是否开启",
    editable: false,
    type: "input"
  },
  {
    prop: "APSN",
    label: "机场所属航站",
    editable: false,
    type:"input"
  },
    {
        prop: "displayStatus",
        label: "状态",
        editable: false,
        type: "select", // 将类型更改为'select'
        options: [
            { label: "启用", value: 1 },
            { label: "禁用", value: 0 },
        ],
    },
]);

const tableData = ref([]);





//分页相关状态
const currentPage = ref(1); // 当前页码，默认为第一页
const pageSize = ref(5); // 每页显示数量，默认为5条
const totalElements = ref(0);

// 初始化时加载第一页数据
onMounted(() => {
  fetchFlightData();
  showPagination.value = true;
});
onUpdated(() => {
});

// 添加分页导航的处理函数，比如上一页、下一页、跳转到特定页
function handleSearchPageChange(page) {
  searchCurrentPage.value = page;
  searchOnSubmit(page); // 重新执行搜索并传递当前页码
}
function handleCurrentChange(page) {
  currentPage.value = page;
  fetchFlightData(page);
}

// 更新fetchUserData函数以支持分页查询
async function fetchFlightData(current = currentPage.value, size = pageSize.value) {
  try {
    const response = await axios.get('/airport/page', {
      params: {
        currentPage: current,
        pageSize: size
      }
    });
    if (!response.data.errorCode || response.data.errorCode === "200") {
      // 更新tableData时，考虑分页数据结构
      //将接口返回的数据通过map方法遍历并转换为新的对象数组
      tableData.value = response.data.data.map(airPort => ({
        ID: airPort.id,
        META_ID: airPort.metaid,
        CODE: airPort.code,
        CNNM: airPort.cnnm,
        ENNM: airPort.ennm,
        AISO: airPort.aiso,
        APSN: airPort.apsn,
          VALID: airPort.valid,
          // 添加新属性用于展示，根据VALID值决定
          displayStatus: airPort.valid === 1 ? '启用' : '禁用',
        editable: false,
      }));
      totalElements.value = response.data.total;
    } else {
      ElMessage.error(response.data.msg || '获取数据失败');
      console.error('Failed to fetch data. ErrorCode:', response.data.errorCode, ', Message:', response.data.msg);
    }
  } catch (error) {
    ElMessage.error('获取数据过程中发生错误');
    console.error('Error fetching data:', error);
  }
}


//模糊查询
const searchCriteria = reactive({
  META_ID: '',
  CNNM: '',
  ENNM: '',
});
const showPagination = ref(true);

const buttonLabel = computed(() => {
  showPagination.value =
      searchCriteria.META_ID.trim() !== ''
      || searchCriteria.CNNM.trim() !== ''
      || searchCriteria.ENNM.trim() !== '';
  return searchCriteria.META_ID.trim() === ''
  && searchCriteria.CNNM.trim() === ''
  && searchCriteria.ENNM.trim() === ''
      ? '查询所有'
      : '条件查询';
});

const searchCurrentPage = ref(1);
const searchPageSize = ref(7);
const searchTotalElements = ref(0);
const showSearchPagination = ref(false);

async function searchOnSubmit() {

  try {
    const response = await axios.get(`/airport/get`, {
      params: {
        ...searchCriteria,
        currentPage: searchCurrentPage.value,
        pageSize: searchPageSize.value,
      }
    });

    if (!response.data.errorCode || response.data.errorCode === "200") {
      tableData.value = response.data.data.map(airPort => ({
        ID: airPort.id,
        META_ID: airPort.metaid,
        CODE: airPort.code,
        CNNM: airPort.cnnm,
        ENNM: airPort.ennm,
        AISO: airPort.aiso,
        APSN: airPort.apsn,
          VALID: airPort.valid,
          // 添加新属性用于展示，根据VALID值决定
          displayStatus: airPort.valid === 1 ? '启用' : '禁用',
        editable: false,
      }));
      searchTotalElements.value = response.data.total;
      if (response.data.total > 10) {
        showSearchPagination.value = true; // 显示搜索结果的分页
      }
      showPagination.value = false; // 隐藏原来的分页
    } else {
      ElMessage.error('查询失败，请检查输入或重试');
      console.error('查询失败:', response.data.message || '未提供错误信息');
    }
  } catch (error) {
    ElMessage.error('查询过程中发生错误');
    console.error('查询错误:', error);
  }
}

//取消
const searchOnReset = async () => {
  searchCriteria.META_ID = "";
  searchCriteria.ENNM = "";
  searchCriteria.CNNM = "";
  await fetchFlightData();
  showPagination.value = true;
  showSearchPagination.value = false;
};

// 添加航班信息的对话框状态
const dialogVisible = ref(false);

// 新航班信息对象
const newFlight = reactive({
  metaid: '',
  code: "",
  cnnm: "",
  ennm: "",
  aiso: "",
  apsn: "",
});

// 添加表单的引用
const addFormRef = ref( null);

// 打开添机场信息的模态框
const openAddDialog = () => {
  dialogVisible.value = true;
};

// 重置添加表单
const resetAddForm = () => {
  newFlight.metaid = '';
  newFlight.code = "";
  newFlight.cnnm = "";
  newFlight.ennm = "";
  newFlight.aiso = "";
  newFlight.apsn = "";
};

// 添加机场信息的处理函数
async function onAddHandler() {
  try {
    // 验证表单
    if (!addFormRef.value) return;

    //  校验航班号必须是6位的数字
    if (!/^[1-9]\d{5}$/.test(newFlight.metaid)) {
      ElMessage.warning('航班号格式不正确，请输入正确的格式[六位数字]');
      return;
    }
    //校验机场是否可用
    if (!/^[OCoc]$/.test(newFlight.aiso)) {
      ElMessage.warning('输入O表示开启，输入C表示关闭，请重新输入');
      return;
    }

    // 发送添加请求到后端
    const response = await axios.post('/airport/add', newFlight);

    if (!response.data.errorCode || response.data.errorCode === "200") {
      ElMessage.success('添加成功');
      dialogVisible.value = false; // 关闭模态框
      await fetchFlightData(); // 刷新表格数据
    } else {
      ElMessage.error(response.data.msg || '添加失败，请重试');
    }
  } catch (error) {
    console.error('Error adding data:', error);
    ElMessage.error('添加过程中发生错误');
  }
}

// 删除航班信息
async function deleteFlightData(ID) {
  // 使用ElMessageBox显示确认对话框
  const confirmResult = await ElMessageBox.confirm(
      '确定要删除这条航班信息吗？',
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
  );
  // 如果用户点击了确认按钮（confirm）
  if (confirmResult === 'confirm') {
    try {
      const response = await axios.delete(`/airport/delete/${ID}`);

      if (!response.data.errorCode || response.data.errorCode === "200") {
        await fetchFlightData();
        ElMessage.success('删除成功');
      } else {
        ElMessage.error('删除失败，请重试');
      }
    } catch (error) {
      console.error('Error deleting data:', error);
      ElMessage.error('删除失败');
    }
  }
  // 如果用户点击取消，则什么都不做，对话框自动关闭
}

//切换表格行进入编辑模式
function handleEdit(row) {
  row.editable = true;
}


// 修改
async function saveEditedRow(row) {
    if (row.displayStatus === '启用'  || row.displayStatus ==='禁用') {
        ElMessage.warning('请再次确认选择一次您的状态');
        return; // 停止执行保存逻辑
    }
  try {
    const updatedFlight = {
      id: row.ID,
      META_ID: row.META_ID,
      code: row.CODE,
      cnnm: row.CNNM,
      ennm: row.ENNM,
      aiso: row.AISO,
      apsn: row.APSN,
        valid: row.displayStatus,

    };

    const response = await axios.put(`/airport/update`, updatedFlight);

    if (!response.data.errorCode || response.data.errorCode === "200") {
      ElMessage.success('更新成功');
      row.editable = false;
      await fetchFlightData();
    } else {
      ElMessage.error(response.data.msg || '更新失败，请重试');
    }
  } catch (error) {
    console.error('Error updating data:', error);
    ElMessage.error('更新过程中发生错误');
  }
}

//取消修改按钮
const cancelEdit = (row) => {
  row.editable = false;
  //    恢复原来数据
  Object.assign(row, {
    ID: row.ID,
    META_ID: row.META_ID,
    CODE: row.CODE,
    CNNM: row.CNNM,
    ENNM: row.ENNM,
    AISO: row.AISO,
    APSN: row.APSN,
  });
  ElMessage.warning('已取消修改');
  fetchFlightData();
};
</script>

<style scoped>
.demo-pagination-block + .demo-pagination-block {
  margin-top: 20px;
}
.demo-pagination-block .demonstration {
  margin-bottom: 16px;
}
</style>